/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package studio.raptor.ddal.core.connection.jdbc;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import studio.raptor.ddal.core.connection.AbstractPooledObjectFactory;
import studio.raptor.ddal.core.connection.ConnectionFactory;

/**
 * @author Sam
 * @since 3.0.0
 */
public class PooledJdbcConnectionFactory extends AbstractPooledObjectFactory implements PooledObjectFactory<JdbcBackendConnection> {

  private ConnectionFactory<JdbcBackendConnection> connectionFactory;

  public PooledJdbcConnectionFactory(ConnectionFactory<JdbcBackendConnection> jdbcConnectionFactory) {
    this.connectionFactory = jdbcConnectionFactory;
  }

  @Override
  public PooledObject<JdbcBackendConnection> makeObject() throws Exception {
    return new DefaultPooledObject<>(this.connectionFactory.createConnection());
  }

  /**
   * 连接池ObjectPool在真正关闭连接时会调用这个方法。
   *
   * @param p Jdbc backend connection wrapped by PooledObject
   * @throws Exception Database access error.
   */
  @Override
  public void destroyObject(PooledObject<JdbcBackendConnection> p) throws Exception {
    p.getObject().reallyClose();
  }

  @Override
  public boolean validateObject(PooledObject<JdbcBackendConnection> p) {
    return p.getObject().validate(getPoolConfig().getCheckQuery(), 0);
  }

  @Override
  public void activateObject(PooledObject<JdbcBackendConnection> p) throws Exception {

  }

  @Override
  public void passivateObject(PooledObject<JdbcBackendConnection> p) throws Exception {

  }
}
